import sockjs from 'sockjs-client';
import stompjs from 'stompjs';
import {fromJson} from '../utils/utils'
import {wsMsg, sockJsMsg} from '../config/config'

/*
channel c4ca4238a0b923820dcc509a6f75849b
extId	extFlag
1    	1      	86475989193850880
1       2       86476192953139200  
1       3       86476224611745792  
*/

function msgClient({channel, tokenId, getRadio, getSend}) {
	this.channel = channel;
	this.tokenId = tokenId;
	this.getRadio = getRadio;
	this.getSend = getSend;
	
	// 初始化(内部函数)
	let _init = () => {
		// 建立socket
		let socket;
		if ('WebSocket' in window) {
			socket = new WebSocket(wsMsg())
		} else if ('MozWebSocket' in window) {
			socket = new MozWebSocket(wsMsg())
		} else {
			socket = new sockjs(sockJsMsg())
		}
		let client = stompjs.over(socket)
		client.debug = () => {}
		client.connect({}, (frame) => {
			// 心跳
			
			// 订阅广播地址
			client.subscribe('/topic/radio/' + channel, (res) => {
				if (this.getRadio) {
					this.getRadio(fromJson(res.body))
				}
			});
			
			// 订阅单点地址
			client.subscribe('/user/' + tokenId + '/' + channel, (res) => {
				if (this.getSend) {
					this.getSend(fromJson(res.body))
				}
			});
			
		})
		return client
	}
	
	// 客户端
	this.client = _init();
	
	// 广播
	this.radio = (message) => {
		this.client.send('/ws/message/radio', {
			channel: this.channel,
			srcTokenId: this.tokenId
		}, message);
	}
	
	// 推送
	this.send = (tarTokenId, message) => {
		this.client.send('/ws/message/send', {
			channel: this.channel,
			srcTokenId: this.tokenId,
			tarTokenId: tarTokenId
		}, message);
	}
	
}